package com.company.LifeCycleThreadPool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 作者  Administrator
 * 时间  2017/6/2 13:45
 * 文件  ThreadPoolsDemo
 * 描述  带有优先级和暂停功能的
 */
public class PausableThreadPoolExecutor extends ThreadPoolExecutor {
	private boolean isPaused;
//	这里只有一把锁；是不是只能控制一个线程
	private ReentrantLock pauseLock = new ReentrantLock();//这个用来加锁
	private Condition unpaused = pauseLock.newCondition();//获取锁状态(比synchronized强) 类似操作Object 的wait/notify等操作

	public PausableThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
	                                  long keepAliveTime, TimeUnit unit,
	                                  BlockingQueue<Runnable> workQueue) {
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
	}

	@Override
	protected void beforeExecute(Thread t, Runnable r) {
		super.beforeExecute(t, r);
		pauseLock.lock();//加锁
		try {
			while (isPaused) unpaused.await();
		} catch (InterruptedException ie) {
			ie.printStackTrace();
			t.interrupt();
		} finally {
			pauseLock.unlock();
		}

	}

	public void pause() {
		pauseLock.lock();
		try {
			isPaused = true;
		} finally {
			pauseLock.unlock();
		}
	}

	public void resume() {
		pauseLock.lock();
		try {
			isPaused = false;
			unpaused.signalAll();
		} finally {
			pauseLock.unlock();
		}
	}
}